<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        .list {
            width: 400px;
            height: 600px;
            border: 1px solid lightgray;
            border-radius: 8px;
            padding: 8px;
            box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
            overflow-y: auto;
            margin: 0 auto;
        }

        .item {
            height: 100px;
            border-bottom: 1px solid lightgray;
            text-align: center;
            line-height: 100px;
        }

        #more {
            height: 40px;
            text-align: center;
            line-height: 40px;
        }
    </style>
</head>

<body>
    <div class="list">
        <div class="list-content"></div>
        <div id="more">加载中...</div>
    </div>
    <script>
        let index = 0;
        let total = 60;
        let count = 20;
        const listContent = document.querySelector('.list-content');
        const list = document.querySelector('.list');
        const more = document.querySelector('#more');

        function loadData() {
            if (index >= total) {
                more.innerText = '已经到底了';
                return;
            }
            let frag = document.createDocumentFragment();
            for (let i = index; i < index + count; i++) {
                let item = document.createElement('div');
                item.innerText = i.toString();
                item.setAttribute('class', 'item');
                frag.appendChild(item);
            }
            // 模拟加载延迟
            setTimeout(() => {
                listContent.appendChild(frag);
                index += count;
                observer.observe(more);
            }, 2000);
        }

        let observer = new IntersectionObserver((e) => {
            if (e[0].isIntersecting) {
                // 取消监听，防止在加载完成前滚动页面重复触发事件
                observer.unobserve(more);
                loadData();
            }

        }, { root: list, threshold: 1 })

        window.onload = function (event) {
            loadData();
        }
    </script>
</body>

</html>